var websock = null;
let rec; // 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let isConnect = false; // 连接标识 避免重复连接
let connectCallBack = null;
let messageCallBack = null;
let closeCallBack = null;

let connect = ( accessToken) => {
	try {
		if (isConnect) {
			return;
		}
		console.log("连接WebSocket");
		let wsUrl;

		if (process.env.NODE_ENV === 'development') {
			// 开发环境：连接到代理服务器
			wsUrl = `wss://www.gykj-bj.com/test-wsim-service/api/ws/${Math.random().toString(36).substr(2, 8)}`;
		} else {
			// 生产环境：直接连接到生产 WebSocket 地址
			wsUrl = `wss://www.gykj-bj.com/test-wsim-service/api/ws/${Math.random().toString(36).substr(2, 8)}`;
		}
		websock = new WebSocket(wsUrl);
		websock.onmessage = function (e) {
			if (e.data === 'pong') return;
			let sendInfo = JSON.parse(e.data);
			// 现在直接转发所有消息给 messageCallBack
			console.log("收到消息:", sendInfo);
			messageCallBack && messageCallBack(sendInfo);
		};

		websock.onclose = function (e) {
			console.log('WebSocket连接关闭');
			isConnect = false; // 断开后修改标识
			closeCallBack && closeCallBack(e);
		};

		websock.onopen = function () {
			console.log("WebSocket连接成功");
			isConnect = true;
			// 发送登录命令
			let loginInfo = {
				requestType: "Register",
				requestId: "12346",
				token: accessToken
			};
			websock.send(JSON.stringify(loginInfo));

			// 调用 connectCallBack
			connectCallBack && connectCallBack();
		};

		// 连接发生错误的回调方法
		websock.onerror = function () {
			console.log('WebSocket连接发生错误');
			isConnect = false; // 连接断开修改标识
			reconnect(accessToken);
		};
	} catch (e) {
		console.log("尝试创建连接失败");
		reconnect( accessToken); // 如果无法连接上webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
	}
};

// 定义重连函数
let reconnect = (wsurl, accessToken) => {
	console.log("尝试重新连接");
	if (isConnect) {
		// 如果已经连上就不在重连了
		return;
	}
	rec && clearTimeout(rec);
	rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
		connect(wsurl, accessToken);
	}, 15000);
};

// 设置关闭连接
let close = (code) => {
	websock && websock.close(code);
};

// 定期发送心跳信号
const heartbeatInterval = setInterval(() => {
	if (isConnect) {
		console.log('发送WebSocket心跳');
		websock.send('ping');  // 向服务器发送心跳消息
	}
}, 20000);  // 每20秒发送一次心跳包

// 实际调用的方法
let sendMessage = (agentData) => {
	if (websock.readyState === websock.OPEN) {
		// 若是ws开启状态
		websock.send(JSON.stringify(agentData));
	} else if (websock.readyState === websock.CONNECTING) {
		// 若是 正在开启状态，则等待1s后重新调用
		setTimeout(function () {
			sendMessage(agentData);
		}, 1000);
	} else {
		// 若未开启 ，则等待1s后重新调用
		setTimeout(function () {
			sendMessage(agentData);
		}, 1000);
	}
};

let onConnect = (callback) => {
	connectCallBack = callback;
};

let onMessage = (callback) => {
	messageCallBack = callback;
};

let onClose = (callback) => {
	closeCallBack = callback;
	clearInterval(heartbeatInterval);
};

// 将方法暴露出去
export {
	connect,
	reconnect,
	close,
	sendMessage,
	onConnect,
	onMessage,
	onClose,
};
